<?php

use Medoo\Medoo;
use QL\QueryList;

/**
 * http://docs.guzzlephp.org/en/stable/request-options.html#query
 * https://medoo.in/api/new
 * http://www.querylist.cc/docs/guide/v4/http-client
 */
chdir(__DIR__);
require_once realpath('..') . '/vendor/autoload.php';
$config = include 'database.php';

echo '爬虫开始' . PHP_EOL;
$db = new Medoo($config);
const BRAND = '北汽新能源';
$db->delete('tDealer', ['sBrand' => BRAND]);
$client = new GuzzleHttp\Client(['timeout' => 0,]);


function get_provinces()
{
    global $client;
    $res = $client->get("http://mmc.prod.bjev.com.cn/cmsapi//configlocation/getAllProvinces?timestap=1551684643066");
    $html = (string)$res->getBody();

    $temp = json_decode($html, true);
    return $temp['result'];
}

function get_cities($province_id)
{
    global $client;
    $res = $client->get("http://mmc.prod.bjev.com.cn/cmsapi//configlocation/getCitiesByProvinceId?timestap=1551688602416&provinceId=${province_id}");
    $html = (string)$res->getBody();

    $temp = json_decode($html, true);
    return $temp['result'];
}

function get_dealers($city_id)
{
    global $client;

    $res = $client->get(
        "http://mmc.prod.bjev.com.cn/cmsapi//cmsdealerinfo2c/getDealerInfoList?timestap=1551687958127&locationId=${city_id}&serialId=&pageSize=10000",
        ['query' => ['cityId' => $city_id]]);
    $html = (string)$res->getBody();

    $temp = json_decode($html, true);
    return $temp['result']['list'];
}

$provinces = get_provinces();
foreach ($provinces as $p) {
    $province_id = $p['id'];
    $province = $p['name'];
    $cites = get_cities($province_id);
    foreach ($cites as $c) {
        $city_id = $c['id'];
        $city = $c['name'];
        $dealers = get_dealers($city_id);
        foreach ($dealers as $item) {
            $db->insert('tDealer', [
                'sDealerName' => $item['dealerFullName'],
                'nBrandID' => $item['dealerId'],
                'sBrand' => BRAND,
                'sProvince' => $province,
                'sCity' => $city,
                'sAddress' => $item['contactAddress'],
                'sSaleCall' => $item['salesPhones'],
                'sLatitude' => $item['latitude'],
                'sLongitude' => $item['longitude'],
                'dUpdateTime' => Medoo::raw('now()'),
                'sManufacturer' => BRAND,
            ]);
            echo "{$item['dealerFullName']}完成" . PHP_EOL;
        }
    }
}

echo '爬虫结束' . PHP_EOL;